package com.ysstech.kettle.init;


import com.ysstech.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.repository.AbstractRepository;
import org.pentaho.di.repository.kdr.KettleDatabaseRepository;
import org.pentaho.di.repository.kdr.KettleDatabaseRepositoryMeta;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;


/**
 * 配置在yml文件中的常量数据
 *
 * @author
 */
@Slf4j
@Configuration
public class KettleConfig {


    @Value("${kettle.datasource.username}")
    public String username;
    @Value("${kettle.datasource.password}")
    public String password;
    @Value("${kettle.datasource.name}")
    public String name;
    @Value("${kettle.datasource.type}")
    public String type;
    @Value("${kettle.datasource.access}")
    public String access;
    @Value("${kettle.datasource.host}")
    public String host;
    @Value("${kettle.datasource.port}")
    public String port;
    @Value("${kettle.datasource.repName}")
    public String repName;
    @Value("${kettle.datasource.repUsername}")
    public String repUsername;
    @Value("${kettle.datasource.repPassword}")
    public String repPassword;
    @Value("${kettle.datasource.logLevel}")
    public String logLevel;
    // kettle执行的路径
    @Value("${kettle.job.path}")
    public String jobPath;
    // kettle执行的名称
    @Value("${kettle.job.name}")
    public String jobName;
    /**
     * repository:kettle资源库
     */

    /**
     * 获取kettle资源库
     *
     * @return
     */
    public AbstractRepository getKettleRepository() throws Exception {
        //初始化kettle环境
        // 获取数据连接元
        DatabaseMeta dataMeta = new DatabaseMeta(name, type, access, host, name, port, username, password);
        // 数据库资源库元
        KettleDatabaseRepositoryMeta drm = new KettleDatabaseRepositoryMeta();
        drm.setConnection(dataMeta);
        drm.setName(repUsername);
        // 初始化并连接到数据库资源库
        KettleDatabaseRepository rep = new KettleDatabaseRepository();
        rep.init(drm);
        // 开始连接资源库
        try {
            // 这里需要r_user表的用户信息
            rep.connect(repUsername, repPassword);
        } catch (Exception e) {
            String msg = "连接数据库资源库失败";
            log.error(msg, e);
            throw new BusinessException("连接数据库资源库失败");
        }
        return rep;
    }
}
